Page({
  data: {
    cart: [],
    allSelected: false,
    totalPrice: 0,
    totalQuantity: 0
  },

  onLoad() {
    this.initCart();
  },

  onShow() {
    this.initCart();
  },

  // 初始化购物车
  initCart() {
    const cart = wx.getStorageSync('cart') || [];
    this.setData({ cart });
    this.updateCartStatus();
  },

  // 更新购物车状态（总价、总数量、全选状态）
  updateCartStatus() {
    const { cart } = this.data;
    let totalPrice = 0;
    let totalQuantity = 0;
    let allSelected = true;
    
    cart.forEach(item => {
      if (item.selected) {
        totalPrice += item.price * item.quantity;
        totalQuantity += item.quantity;
      }
      if (!item.selected) {
        allSelected = false;
      }
    });
    
    this.setData({
      totalPrice,
      totalQuantity,
      allSelected
    });
  },

  // 商品选择状态变化
  onSelectChange(event) {
    const { id } = event.currentTarget.dataset;
    const { cart } = this.data;
    const index = cart.findIndex(item => item.id === id);
    
    if (index !== -1) {
      cart[index].selected = !cart[index].selected;
      this.setData({ cart });
      this.updateCartStatus();
      wx.setStorageSync('cart', cart);
    }
  },

  // 全选/取消全选
  onSelectAll() {
    const { cart, allSelected } = this.data;
    cart.forEach(item => {
      item.selected = !allSelected;
    });
    this.setData({ cart });
    this.updateCartStatus();
    wx.setStorageSync('cart', cart);
  },

  // 数量变化
  onQuantityChange(event) {
    console.log(event)
    const { id } = event.currentTarget.dataset;
    const value = event.detail; // 2
    const { cart } = this.data;
    const index = cart.findIndex(item => item.id === id);
    
    if (index !== -1) {
      cart[index].quantity = value;
      this.setData({ cart });
      this.updateCartStatus();
      wx.setStorageSync('cart', cart);
    }
  },

  // 删除商品
  onDelete(event) {
    const { id } = event.currentTarget.dataset;
    const { cart } = this.data;
    const newCart = cart.filter(item => item.id !== id);
    
    wx.showModal({
      title: '确认删除',
      content: '确定要删除此商品吗？',
      success: (res) => {
        if (res.confirm) {
          this.setData({ cart: newCart });
          this.updateCartStatus();
          wx.setStorageSync('cart', newCart);
          wx.showToast({
            title: '已删除',
            icon: 'success'
          });
        }
      }
    });
  },

  // 结算
  onCheckout() {
    const { cart, totalPrice, totalQuantity } = this.data;
    const selectedItems = cart.filter(item => item.selected);
    
    if (selectedItems.length === 0) {
      wx.showToast({
        title: '请选择商品',
        icon: 'none'
      });
      return;
    }
    
    wx.showModal({
      title: '结算确认',
      content: `共${totalQuantity}件商品，总计：¥${totalPrice.toFixed(2)}`,
      success: (res) => {
        if (res.confirm) {
          // 模拟支付成功
          setTimeout(() => {
            // 移除已结算的商品
            const newCart = cart.filter(item => !item.selected);
            this.setData({ cart: newCart });
            this.updateCartStatus();
            wx.setStorageSync('cart', newCart);
            
            wx.showToast({
              title: '支付成功',
              icon: 'success'
            });
          }, 1000);
        }
      }
    });
  }
});    